package cn.edu.hatu.bookshop.controller;

import cn.edu.hatu.bookshop.entity.Book;
import cn.edu.hatu.bookshop.entity.TempBook;
import cn.edu.hatu.bookshop.service.BookService;
import cn.edu.hatu.bookshop.service.ClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class NavbarController {
    private BookService bookService;
    private ClassifyService classifyService;
    @Autowired
    public void setClassifyService(ClassifyService classifyService) {
        this.classifyService = classifyService;
    }
    @Autowired
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }
    @RequestMapping("/homePage")
    public String homePage(Model model){
        Random random = new Random();
        int classifyId = random.nextInt(6)+1;
        System.out.println("classifyID :"+classifyId);
        List<Book> books = bookService.getBooksByClassifyId(classifyId);
        String classifyName = classifyService.getClassifyName(classifyId);
        System.out.println(classifyName);
        model.addAttribute("books", books);
        model.addAttribute("classifyName",classifyName);
        return "Customer/HomePage";
    }
    @RequestMapping("/searchBook")
    public String searchBook(Model model, HttpServletRequest request, RedirectAttributes attr){
        String regex = request.getParameter("search");
        System.out.println("search:"+regex);
        List<Book> findBooks = bookService.fuzzyQuery(regex);
        if(findBooks.size()==0){
            return "Customer/SearchBook/SearchBookFailed";
        }else {
            List<TempBook> books = new ArrayList<TempBook>();
            for (Book b:findBooks
            ) {
                System.out.println("book:"+b.getBookName());
                String classifyName = classifyService.getClassifyName(b.getClassifyId());
                TempBook tempBook = new TempBook(b.getBookId(),b.getBookName(),classifyName,b.getBookAuthor(),b.getPrice());
                books.add(tempBook);
            }
            model.addAttribute("books",books);
            return "Customer/SearchBook/SearchBookSuccess";
        }

    }
}
